<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/29
 * Time: 11:01
 */
namespace App\handlers;

use Workerman\Lib\Timer;
use Workerman\Connection\AsyncTcpConnection;

// 心跳间隔10秒
define('HEARTBEAT_TIME', 10);

class WorkermanHandler
{
    protected $sub_str='market.btcusdt.kline.1min';
    // 处理客户端连接
    public function onConnect($connection)
    {
        echo "new connection from ip " . $connection->getRemoteIp() . "\n";

    }

    // 处理客户端消息
    public function onMessage($connection, $data)
    {
        // 向客户端发送hello $data
        $connection->send('Hello, your send message is: ' . $data);
    }

    // 处理客户端断开
    public function onClose($connection)
    {
        echo "connection closed from ip {$connection->getRemoteIp()}\n";
    }

    public function onWorkerStart($worker)
    {
        $con = new AsyncTcpConnection('ws://api.huobi.pro:443/ws');
        $con->transport = 'ssl';
        $con->onConnect = function($con) {
            $data = json_encode([
                'sub' => $this->sub_str,
                'id' => 'depth' . time()
            ]);
            $con->send($data);
        };

        $con->onMessage = function($con, $data) {
            $data = gzdecode($data);
            $data = json_decode($data, true);
            if(isset($data['ping'])) {
                $con->send(json_encode([
                    "pong" => $data['ping']
                ]));
            }else{
                //call_user_func_array($GLOBALS['callback'], array($data));
                exec('php7 artisan wk start');
            }
        };

        $con->connect();
    }
}